package com.love.cloud.auth.service.impl;

import com.love.cloud.admin.api.dto.UserInfo;
import com.love.cloud.admin.api.provider.RemoteUserProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户详细信息
 *
 * @author hongdongqu
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MyQRCodeServiceImpl extends BaseUserDetailServiceImpl {
	@DubboReference(version = "1.0.0", timeout = 30000)
	private RemoteUserProvider remoteUserProvider;


	@Override
	protected UserInfo getUser(String QRCode) {
		String[] s = QRCode.split("_");
		try {
			if(s.length==2){
				if("ZZDQr".equals(s[1])){
					UserInfo info = remoteUserProvider.infoByZZDQRCode(s[0],false);
					if(info==null){
						throw new UsernameNotFoundException("未查询到该用户");
					}
					return info;
				}else if("ZZDQrAdd".equals(s[1])){
					//下面为在本系统中的用户体系不存在，但是能通过浙政钉查询出来的默认添加进去
					UserInfo info = remoteUserProvider.infoByZZDQRCode(s[0],true);
					if(info==null){
						throw new UsernameNotFoundException("未查询到该用户");
					}
					return info;
				}else if("DDQr".equals(s[1])){
					//todo 普通钉钉扫码
				}else if("WeChatQr".equals(s[1])){
					//todo 微信扫码
				}
			}else{
				throw new UsernameNotFoundException("解析用户信息失败请传入正确的参数");
			}
		}catch (Exception e){
			throw new UsernameNotFoundException(e.getMessage());
		}
		return null;
	}

	/**
	 * QRCode无法通过缓存进行检索所以移除缓存逻辑
	 * @param var1
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	public UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException {
		UserInfo result = getUser(var1);
		UserDetails userDetails = getUserDetails(result);
		return userDetails;
	}
}
